import {
  computed, ref, shallowRef, unref, watch
} from 'vue';
import { resolveRef, tryOnScopeDispose, useSupported } from './shared';

export function useSpeechSynthesis(text, options = {}) {
  const {
    // 音高
    pitch = 1,
    // 播放速度
    rate = 1,
    // 音量
    volume = 1
  } = options;
  // 是否支持 speechSynthesis api
  const synth = window && window.speechSynthesis;
  const isSupported = useSupported(() => synth);
  // 是否播放
  const isPlaying = ref(false);
  // 状态
  const status = ref('init');
  const spokenText = resolveRef(text || '');
  // 语言
  const lang = resolveRef(options.lang || 'en-US');
  // 错误 shallowRef : ref() 的浅层作用形式。
  const error = shallowRef(undefined);
  // 切换播放状态
  const toggle = (value = !isPlaying.value) => {
    isPlaying.value = value;
  };
  // 设置语音服务的属性
  const bindEventsForUtterance = (utterance2) => {
    utterance2.lang = unref(lang);
    utterance2.voice = unref(options.voice) || null;
    utterance2.pitch = pitch;
    utterance2.rate = rate;
    utterance2.volume = volume;
    utterance2.onstart = () => {
      console.log('onstart');
      isPlaying.value = true;
      status.value = 'play';
    };
    utterance2.onpause = () => {
      console.log('onpause');
      isPlaying.value = false;
      status.value = 'pause';
    };
    utterance2.onresume = () => {
      console.log('onresume');
      isPlaying.value = true;
      status.value = 'play';
    };
    utterance2.onend = () => {
      console.log('onend');
      isPlaying.value = false;
      status.value = 'end';
    };
    utterance2.onerror = (event) => {
      error.value = event;
    };
  };
  // 语音请求对象
  // 什么时候这个值会更新 ??
  const utterance = computed(() => {
    isPlaying.value = false;
    status.value = 'init';
    console.log('utterance 更新');
    // Web Speech API的SpeechSynthesisUtterance接口表示一个语音请求。
    // 它包含语音服务应该读取的内容以及如何读取的信息(例如语言、音高和音量)。
    const newUtterance = new SpeechSynthesisUtterance(spokenText.value);
    bindEventsForUtterance(newUtterance);
    return newUtterance;
  });
  const speak = () => {
    synth.cancel();
    utterance.value && synth.speak(utterance.value);
  };
  const stop = () => {
    synth.cancel();
    isPlaying.value = false;
  };

  if (isSupported.value) {
    bindEventsForUtterance(utterance.value);
    watch(lang, (lang2) => {
      if (utterance.value && !isPlaying.value) utterance.value.lang = lang2;
    });
    if (options.voice) {
      watch(options.voice, () => {
        synth.cancel();
      });
    }
    watch(isPlaying, () => {
      if (isPlaying.value) synth.resume();
      else synth.pause();
    });
  }
  tryOnScopeDispose(() => {
    isPlaying.value = false;
  });
  return {
    // 是否支持
    isSupported,
    // 是否播放
    isPlaying,
    // 播放状态
    status,
    // 语音请求对象
    utterance,
    // 错误信息
    error,
    // 停止播放
    stop,
    // 切换播放状态
    toggle,
    // 开始播放
    speak
  };
}
